home *** CD-ROM | disk | FTP | other *** search
/ Languguage OS 2 / Languguage OS II Version 10-94 (Knowledge Media)(1994).ISO / gnu / shllutil.lha / shellutils-1.8 / src / basename.c next >
C/C++ Source or Header  |  1991-08-29  |  2KB  |  79 lines

  1. /* basename -- strip directory and suffix from filenames
  2.    Copyright (C) 1990, 1991 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Usage: basename name [suffix]
  19.    NAME is a pathname; SUFFIX is a suffix to strip from it.
  20.  
  21.    basename /usr/foo/lossage/functions.l
  22.    => functions.l
  23.    basename /usr/foo/lossage/functions.l .l
  24.    => functions
  25.    basename functions.lisp p
  26.    => functions.lis */
  27.  
  28. #include <stdio.h>
  29. #include <sys/types.h>
  30. #include "system.h"
  31.  
  32. char *basename ();
  33. void remove_suffix ();
  34. void strip_trailing_slashes ();
  35.  
  36. void
  37. main (argc, argv)
  38.      int argc;
  39.      char **argv;
  40. {
  41.   char *name;
  42.  
  43.   if (argc == 1 || argc > 3)
  44.     {
  45.       fprintf (stderr, "Usage: %s name [suffix]\n", argv[0]);
  46.       exit (1);
  47.     }
  48.  
  49.   strip_trailing_slashes (argv[1]);
  50.  
  51.   name = basename (argv[1]);
  52.  
  53.   if (argc == 3)
  54.     remove_suffix (name, argv[2]);
  55.  
  56.   puts (name);
  57.  
  58.   exit (0);
  59. }
  60.  
  61. /* Remove SUFFIX from the end of NAME if it is there, unless NAME
  62.    consists entirely of SUFFIX. */
  63.  
  64. void
  65. remove_suffix (name, suffix)
  66.      register char *name, *suffix;
  67. {
  68.   register char *np, *sp;
  69.  
  70.   np = name + strlen (name);
  71.   sp = suffix + strlen (suffix);
  72.  
  73.   while (np > name && sp > suffix)
  74.     if (*--np != *--sp)
  75.       return;
  76.   if (np > name)
  77.     *np = '\0';
  78. }
  79.